package com.yf.catcafe.service.impl;

import com.yf.catcafe.common.OrderNoGenerator;
import com.yf.catcafe.mapper.CoffesMapper;
import com.yf.catcafe.mapper.OrdersMapper;
import com.yf.catcafe.pojo.dto.CafeDto;
import com.yf.catcafe.pojo.dto.OrderVo;
import com.yf.catcafe.pojo.dto.SeckillCafeDto;
import com.yf.catcafe.pojo.enity.Cafe;
import com.yf.catcafe.pojo.enity.Order;
import com.yf.catcafe.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private CoffesMapper coffesMapper;

    @Override
    public OrderVo insert(CafeDto cafeDto) {
        Order order=new Order();
        BeanUtils.copyProperties(cafeDto,order);
        String orderNo = OrderNoGenerator.generateOrderNo();
        order.setOrderNo(orderNo);
        order.setOrderTime(LocalDateTime.now());
        order.setUserId(cafeDto.getUserId());
        order.setFlavor(cafeDto.getFlavor());
        order.setNote(cafeDto.getNote());
        order.setTotal(cafeDto.getTotal());
        order.setNumber(cafeDto.getQuantity());
        order.setCafeName(cafeDto.getName());
        ordersMapper.insert(order);

        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(order.getOrderNo());
        orderVo.setOrderTime(order.getOrderTime());
        orderVo.setUserId(order.getUserId());
        orderVo.setFlavor(order.getFlavor());
        orderVo.setNote(order.getNote());
        orderVo.setNumber(order.getNumber());
        orderVo.setTotal(order.getTotal());
        return orderVo;
    }

    @Override
    public List<Order> query() {
        List<Order> orders=ordersMapper.query();
        return orders;
    }

    @Override
    public void delete(Long id) {
        ordersMapper.delete(id);
    }

    @Override
    public void seckillinsert(SeckillCafeDto seckillCafeDto) {
        Long userId = seckillCafeDto.getUserId();
        Long coffeeId = seckillCafeDto.getCoffeeId();
        Cafe cafe = coffesMapper.getDetails(coffeeId);
        Order order=new Order();
        order.setOrderNo(OrderNoGenerator.generateOrderNo());
        order.setOrderTime(LocalDateTime.now());
        order.setUserId(userId);
        order.setCafeName(cafe.getName());
        order.setFlavor("原味");
        order.setNumber(1);
        order.setNote("无");
        order.setTotal(cafe.getPrice().divide(new BigDecimal("2")));
        ordersMapper.seckillInsert(order);
    }


}
